import { AudioClip, AudioSource, Component, resources, _decorator } from 'cc';
const { ccclass } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {
  // resources里的音频资源路径数组
  private audioClips: string[] = [
    '32_1', // 不需要加扩展名
    '32_2', // 不需要加扩展名
  ];

  // 保存 AudioSource 组件的数组
  private audioSources: AudioSource[] = [];

  onLoad() {
    // 预加载所有音频资源
    this.audioClips.forEach((path) => {
      resources.load(path, AudioClip, (err, clip) => {
        if (err) {
          console.error('Failed to load audio clip:', path, err);
        } else {
          console.log('Audio clip loaded:', path);
          // 创建 AudioSource 组件并保存
          const audioSource = this.node.addComponent(AudioSource);
          audioSource.clip = clip;
          this.audioSources.push(audioSource);
        }
      });
    });

    setTimeout(() => {
      this.playAllAudios();
    }, 2000);
  }

  playAllAudios() {
    this.audioSources.forEach((audioSource) => {
      audioSource.play();
      console.log('Playing audio:', audioSource.clip.name);
    });
  }

  stopAllAudios() {
    this.audioSources.forEach((audioSource) => {
      audioSource.stop();
      console.log('Stopped audio:', audioSource.clip.name);
    });
  }
}
